<?php
/**
 *@作者:MissZhang
 *@邮箱:<787727147@qq.com>
 *@创建时间:2021/7/3 上午9:14
 *@说明:商品控制器
 */
namespace app\admin\controller;


use app\common\model\ConvertGoods;
use app\common\model\FosterGoods;
use app\common\model\GoodsCategory;
use app\common\model\GoodsType;
use app\common\model\FosterGoodsCategory;
use app\common\model\JifenGoods;
use app\common\model\MonitorClass;
use app\common\model\Monitors;
use app\common\model\Shipping;
use app\common\model\Spec;
use app\common\model\SpecItem;
use app\common\model\StockGoods;
use app\common\model\Wallet;
use app\common\util\AdminException;
use app\common\util\HttpClient;
use think\App;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class Goods extends Base
{
    //商品列表
    public function goods_list(){
        // 搜索条件
        $where = [];
        $cat_id = input('cat_id');
        $is_on_sale = input('is_on_sale');
        $keyword = input('keyword');
        if ($cat_id){
            $cat_level=Db::name('goods_category')->where('id',$cat_id)->value('level');
            $where[]=["cat_id_{$cat_level}",'=',$cat_id];
        }
        if ($is_on_sale!=''){
            if ($is_on_sale==-4){
                $where[]=['is_on_sale','=',0];
            }else{
                $where[]=['is_on_sale','=',$is_on_sale];
            }
        }
        if ($keyword){
            $where[]=['goods_name|goods_sn','like',"%$keyword%"];
        }
        $goods=new \app\common\model\Goods();
        $list = $goods->where($where)->order('goods_id desc')->paginate([
            'query'=>['is_on_sale'=>$is_on_sale,'keyword'=>$keyword,'cat_id'=>$cat_id],
            'list_rows'=>$this->page_size
        ]);
        $categoryList = $goods->getSortCategory();
        // 获取分页显示
        $page = $list->render();
        View::assign('list', $list);
        View::assign('page', $page);
        View::assign('categoryList', $categoryList);
        return view();
    }
    //添加编辑商品
    public function add_edit_goods(){
        $goods_id=input('goods_id');
        $is_seckill=0;
        $goods=new \app\common\model\Goods();
        if ($goods_id){
            $info=$goods->find($goods_id);
            if ($info['seckill_start_time'] && $info['seckill_end_time'] && $info['seckill_price']){
                $is_seckill=1;
            }
//            $is_seckill=$info->is_seckill?1:0;
            if ($info['goods_images']){
                $arr=['mp4','3gp'];
                foreach ($info['goods_images'] as $image){
                    $pathInfo=pathinfo($image['image_url']);
                    $fileValueSuffix=strtolower($pathInfo['extension']);
                    if (in_array($fileValueSuffix,$arr)){
                        $map['type']='video';
                    }else{
                        $map['type']='image';
                    }
                    $map['src']=$image['image_url'];
                    $images[]=$map;
                }
            }
        }else{
            $info['goods_type']=1;
            $info['is_on_sale']=1;
        }
        if (IS_POST){
            $data=input('post.');
            try {
                validate(\app\admin\validate\Goods::class)->batch(true)->check($data);
            }catch (ValidateException $e){
                $error=$e->getError();
                $values=array_values($error);
                $result['result']=$error;
                throw new AdminException($values[0],10,$result);
            }
            if ($data['is_seckill']==0){
                $data['seckill_start_time']=0;
                $data['seckill_end_time']=0;
                $data['seckill_price']=0;
            }else{
                $data['seckill_start_time']=strtotime($data['seckill_start_time']);
                $data['seckill_end_time']=strtotime($data['seckill_end_time']);
            }
            if ($goods_id){
                $res=$info->save($data);
                $goodsModel=$info;
            }else{
                $res=$goods->save($data);
                $goodsModel=$goods;
            }
            if ($res){
                adminLog($goods_id?"编辑商品":"添加商品");
                $goodsModel->afterSave($goodsModel->goods_id);
                $data['url']=url('Goods/goods_list')->build();
                throw new AdminException('操作成功',1,$data);
            }else{
                throw new AdminException('操作失败');
            }
        }
        $cat_list = GoodsCategory::where("parent_id",0)->select();
        $cat_list2=[];
        if ($info['cat_id_2']){
            //查出二级分类
            $cat_list2 = GoodsCategory::where("parent_id",$info['cat_id_1'])->select();
        }
        $goodsType = GoodsType::select();
        $store_list=\app\common\model\Store::where('status=1')->column('store_id,store_name');
        View::assign('store_list', $store_list);
        View::assign('info', $info);
        View::assign('cat_list', $cat_list);
        View::assign('cat_list2', $cat_list2);
        View::assign('goodsType', $goodsType);
        View::assign('images', $images);
        View::assign('is_seckill', $is_seckill);
        return view();
    }
    //删除商品
    public function delGoods()
    {
        $ids = input('post.ids','');
        if (empty($ids)){
            throw new AdminException('请选择数据');
        }
        $ids_arr=implode(',',$ids);
        $goods_ids = rtrim($ids_arr,",");
        // 判断此商品是否有订单
        $ordergoods_count = Db::name('order_goods')->whereIn('goods_id',$goods_ids)->group('goods_id')->column('goods_id');
        if($ordergoods_count)
        {
            $goods_count_ids = implode(',',$ordergoods_count);
            throw new AdminException("ID为【{$goods_count_ids}】的商品有订单,不得删除!");
        }
        // 删除此商品
        Db::name("goods")->whereIn('goods_id',$goods_ids)->delete();  //商品表
//        Db::name("cart")->whereIn('goods_id',$goods_ids)->delete();  // 购物车
        Db::name("goods_images")->whereIn('goods_id',$goods_ids)->delete();  //商品相册
        Db::name("spec_goods_price")->whereIn('goods_id',$goods_ids)->delete();  //商品规格
        Db::name("spec_image")->whereIn('goods_id',$goods_ids)->delete();  //商品规格图片
        Db::name("goods_collect")->whereIn('goods_id',$goods_ids)->delete();  //商品收藏
        Db::name("goods_visit")->whereIn('goods_id',$goods_ids)->delete();  //浏览足迹
        adminLog("删除商品");
        throw new AdminException('操作成功',1);
    }
    //审核商品
    public function check_goods(){
        $ids=input('ids');
        $is_on_sale=input('is_on_sale');
        if (empty($ids)){
            throw new AdminException('请选择数据');
        }
        if (!in_array($is_on_sale,[-3,-2,-1,0,1])){
            throw new AdminException('提交参数有误');
        }
        $update['is_on_sale']=$is_on_sale;
        $res=\app\common\model\Goods::whereIn('goods_id',$ids)->save($update);
        throw new AdminException('操作成功',1);
    }
    //兑换商品列表
    public function convert_goods_list(){
        // 搜索条件
        $where = [];
        $is_on_sale = input('is_on_sale');
        $keyword = input('keyword');
        if ($is_on_sale!=''){
            $where[]=['is_on_sale','=',$is_on_sale];
        }
        if ($keyword){
            $where[]=['goods_name','like',"%$keyword%"];
        }
        $goods=new ConvertGoods();
        $list = $goods->where($where)->order('goods_id desc')->paginate([
            'query'=>['is_on_sale'=>$is_on_sale,'keyword'=>$keyword],
            'list_rows'=>$this->page_size
        ]);
        // 获取分页显示
        $page = $list->render();
        View::assign('list', $list);
        View::assign('page', $page);
        return view();
    }
    //添加编辑兑换商品
    public function add_edit_convert_goods(){
        $goods_id=input('goods_id');
        $images=[];
        $goods=new ConvertGoods();
        if ($goods_id){
            $info=$goods->find($goods_id);
            $info['pinkage']=$info['ship_id']>0?0:1;
            if ($info['goods_imgs']){
                $arr=['mp4','3gp'];
                foreach ($info['goods_imgs'] as $image){
                    $pathInfo=pathinfo($image);
                    $fileValueSuffix=strtolower($pathInfo['extension']);
                    if (in_array($fileValueSuffix,$arr)){
                        $map['type']='video';
                    }else{
                        $map['type']='image';
                    }
                    $map['src']=$image;
                    $images[]=$map;
                }
            }
        }else{
            $info['is_on_sale']=1;
            $info['pinkage']=1;
        }
        if (IS_POST){
            $data=input('post.');
            try {
                validate(\app\admin\validate\ConvertGoods::class)->batch(true)->check($data);
            }catch (ValidateException $e){
                $error=$e->getError();
                $values=array_values($error);
                $result['result']=$error;
                throw new AdminException($values[0],10,$result);
            }
            $data['ship_id']=$data['pinkage']==0?$data['ship_id']:0;
            if ($goods_id){
                $res=$info->save($data);
                $new_goods_id=$goods_id;
            }else{
                $res=$goods->save($data);
                $new_goods_id=$goods->goods_id;
            }
            if ($res){
                $goods_sn = "CSMC".str_pad($new_goods_id,7,"0",STR_PAD_LEFT);
                Db::name('convert_goods')->where("goods_id = $new_goods_id and goods_sn = ''")->save(["goods_sn"=>$goods_sn]); // 根据条件更新记录
                adminLog($goods_id?"编辑兑换商品":"添加兑换商品");
                $data['url']=url('Goods/convert_goods_list')->build();
                throw new AdminException('操作成功',1,$data);
            }else{
                throw new AdminException('操作失败');
            }
        }
        $wallet=Wallet::where('1=1')->column('id,name');
        $shipping_list=Shipping::where('1=1')->column('id,name');
        View::assign('wallet', $wallet);
        View::assign('shipping_list', $shipping_list);
        View::assign('info', $info);
        View::assign('images', $images);
        return view();
    }
    //删除兑换商品
    public function delDhGoods()
    {
        $ids = input('post.ids','');
        if (empty($ids)){
            throw new AdminException('请选择数据');
        }
        $ids_arr=implode(',',$ids);
        $goods_ids = rtrim($ids_arr,",");
        // 判断此商品是否有订单
        $ordergoods_count = Db::name('convert_order')->whereIn('goods_id',$goods_ids)->column('goods_id');
        if($ordergoods_count) {
            $goods_count_ids = implode(',',$ordergoods_count);
            throw new AdminException("ID为【{$goods_count_ids}】的商品有订单,不得删除!");
        }
        // 删除此商品
        Db::name("convert_goods")->whereIn('goods_id',$goods_ids)->delete();  //商品表
        adminLog("删除兑换商品");
        throw new AdminException('操作成功',1);
    }
    //积分商品列表
    public function jifen_goods_list(){
        // 搜索条件
        $where = [];
        $is_on_sale = input('is_on_sale');
        $keyword = input('keyword');
        if ($is_on_sale!=''){
            $where[]=['is_on_sale','=',$is_on_sale];
        }
        if ($keyword){
            $where[]=['goods_name','like',"%$keyword%"];
        }
        $goods=new JifenGoods();
        $list = $goods->where($where)->order('goods_id desc')->paginate([
            'query'=>['is_on_sale'=>$is_on_sale,'keyword'=>$keyword],
            'list_rows'=>$this->page_size
        ]);
        // 获取分页显示
        $page = $list->render();
        View::assign('list', $list);
        View::assign('page', $page);
        return view();
    }
    //添加编辑积分商品
    public function add_edit_jifen_goods(){
        $goods_id=input('goods_id');
        $images=[];
        $goods=new JifenGoods();
        if ($goods_id){
            $info=$goods->find($goods_id);
            if ($info['goods_imgs']){
                $arr=['mp4','3gp'];
                foreach ($info['goods_imgs'] as $image){
                    $pathInfo=pathinfo($image);
                    $fileValueSuffix=strtolower($pathInfo['extension']);
                    if (in_array($fileValueSuffix,$arr)){
                        $map['type']='video';
                    }else{
                        $map['type']='image';
                    }
                    $map['src']=$image;
                    $images[]=$map;
                }
            }
        }else{
            $info['is_on_sale']=1;
        }
        if (IS_POST){
            $data=input('post.');
            try {
                validate(\app\admin\validate\JifenGoods::class)->batch(true)->check($data);
            }catch (ValidateException $e){
                $error=$e->getError();
                $values=array_values($error);
                $result['result']=$error;
                throw new AdminException($values[0],10,$result);
            }
            if ($goods_id){
                $res=$info->save($data);
                $new_goods_id=$goods_id;
            }else{
                $res=$goods->save($data);
                $new_goods_id=$goods->goods_id;
            }
            if ($res){
                $goods_sn = "CSMC".str_pad($new_goods_id,7,"0",STR_PAD_LEFT);
                Db::name('jifen_goods')->where("goods_id = $new_goods_id and goods_sn = ''")->save(["goods_sn"=>$goods_sn]); // 根据条件更新记录
                adminLog($goods_id?"编辑积分商品":"添加积分商品");
                $data['url']=url('Goods/jifen_goods_list')->build();
                throw new AdminException('操作成功',1,$data);
            }else{
                throw new AdminException('操作失败');
            }
        }
        View::assign('info', $info);
        View::assign('images', $images);
        return view();
    }
    //删除积分商品
    public function delJfGoods()
    {
        $ids = input('post.ids','');
        if (empty($ids)){
            throw new AdminException('请选择数据');
        }
        $ids_arr=implode(',',$ids);
        $goods_ids = rtrim($ids_arr,",");
        // 判断此商品是否有订单
        $ordergoods_count = Db::name('jifen_order')->whereIn('goods_id',$goods_ids)->column('goods_id');
        if($ordergoods_count)
        {
            $goods_count_ids = implode(',',$ordergoods_count);
            throw new AdminException("ID为【{$goods_count_ids}】的商品有订单,不得删除!");
        }
        // 删除此商品
        Db::name("jifen_goods")->whereIn('goods_id',$goods_ids)->delete();  //商品表
        adminLog("删除礼品商品");
        throw new AdminException('操作成功',1);
    }
    //进货商品列表
    public function stock_goods_list(){
        // 搜索条件
        $where = [];
        $is_on_sale = input('is_on_sale');
        $keyword = input('keyword');
        if ($is_on_sale!=''){
            $where[]=['is_on_sale','=',$is_on_sale];
        }
        if ($keyword){
            $where[]=['goods_name','like',"%$keyword%"];
        }
        $goods=new StockGoods();
        $list = $goods->where($where)->order('goods_id desc')->paginate([
            'query'=>['is_on_sale'=>$is_on_sale,'keyword'=>$keyword],
            'list_rows'=>$this->page_size
        ]);
        // 获取分页显示
        $page = $list->render();
        View::assign('list', $list);
        View::assign('page', $page);
        return view();
    }
    //添加编辑进货商品
    public function add_edit_stock_goods(){
        $goods_id=input('goods_id');
        $images=[];
        $goods=new StockGoods();
        if ($goods_id){
            $info=$goods->find($goods_id);
            if ($info['goods_imgs']){
                $arr=['mp4','3gp'];
                foreach ($info['goods_imgs'] as $image){
                    $pathInfo=pathinfo($image);
                    $fileValueSuffix=strtolower($pathInfo['extension']);
                    if (in_array($fileValueSuffix,$arr)){
                        $map['type']='video';
                    }else{
                        $map['type']='image';
                    }
                    $map['src']=$image;
                    $images[]=$map;
                }
            }
        }else{
            $info['is_on_sale']=1;
        }
        if (IS_POST){
            $data=input('post.');
            try {
                validate(\app\admin\validate\StockGoods::class)->batch(true)->check($data);
            }catch (ValidateException $e){
                $error=$e->getError();
                $values=array_values($error);
                $result['result']=$error;
                throw new AdminException($values[0],10,$result);
            }
            if ($goods_id){
                $res=$info->save($data);
                $new_goods_id=$goods_id;
            }else{
                $res=$goods->save($data);
                $new_goods_id=$goods->goods_id;
            }
            if ($res){
                $goods_sn = "CSMC".str_pad($new_goods_id,7,"0",STR_PAD_LEFT);
                Db::name('stock_goods')->where("goods_id = $new_goods_id and goods_sn = ''")->save(["goods_sn"=>$goods_sn]); // 根据条件更新记录
                adminLog($goods_id?"编辑进货商品":"添加进货商品");
                $data['url']=url('Goods/stock_goods_list')->build();
                throw new AdminException('操作成功',1,$data);
            }else{
                throw new AdminException('操作失败');
            }
        }
        $wallet=Wallet::where('1=1')->column('id,name');
        View::assign('wallet', $wallet);
        View::assign('info', $info);
        View::assign('images', $images);
        return view();
    }
    //删除进货商品
    public function delStockGoods()
    {
        $ids = input('post.ids','');
        if (empty($ids)){
            throw new AdminException('请选择数据');
        }
        $ids_arr=implode(',',$ids);
        $goods_ids = rtrim($ids_arr,",");
        // 判断此商品是否有订单
        $ordergoods_count = Db::name('stock_order')->whereIn('goods_id',$goods_ids)->column('goods_id');
        if($ordergoods_count)
        {
            $goods_count_ids = implode(',',$ordergoods_count);
            throw new AdminException("ID为【{$goods_count_ids}】的商品有订单,不得删除!");
        }
        // 删除此商品
        Db::name("stock_goods")->whereIn('goods_id',$goods_ids)->delete();  //商品表
        adminLog("删除礼品商品");
        throw new AdminException('操作成功',1);
    }
    //认养商品分类
    public function foster_goods_category(){
        // 搜索条件
        $where = [];
        $is_show=input('is_show');
        $keyword=input('keyword');
        if ($is_show!=''){
            $where[]=['is_show','=',$is_show];
        }
        if ($keyword){
            $where[]=['name','like',"%$keyword%"];
        }
        $goods_category=new FosterGoodsCategory();
        $list=$goods_category::where($where)->paginate([
            'query'=>['is_show'=>$is_show,'keyword'=>$keyword],
            'list_rows'=>$this->page_size
        ]);
        // 获取分页显示
        $page = $list->render();
        View::assign('list', $list);
        View::assign('page', $page);
        return view();
    }
    //添加编辑认养商品分类
    public function add_edit_foster_goods_category(){
        $id=input('id');
        $goods_category=new FosterGoodsCategory();
        if ($id){
            $info=$goods_category->find($id);
        }else{
            $info['is_show']=1;
        }
        if (IS_POST){
            $data=input('post.');
            try {
                validate(\app\admin\validate\FosterGoodsCategory::class)->batch(true)->check($data);
            }catch (ValidateException $e){
                $error=$e->getError();
                $values=array_values($error);
                throw new AdminException($values[0],10,['result'=>$error]);
            }
            if ($id){
                $res=$info->save($data);
            }else{
                $res=$goods_category->save($data);
            }
            if ($res){
                adminLog($id?"编辑认养商品分类":"添加认养商品分类");
                throw new AdminException('操作成功',1,['url'=>url('Goods/foster_goods_category')->build()]);
            }else{
                throw new AdminException('操作失败');
            }
        }
        $cat_select = $goods_category->column('name,id');
        View::assign('cat_select',$cat_select);
        View::assign('info', $info);
        return view();
    }
    //认养商品列表
    public function foster_goods_list(){
        // 搜索条件
        $where = [];
        $is_on_sale = input('is_on_sale');
        $keyword = input('keyword');
        if ($is_on_sale!=''){
            if ($is_on_sale==-4){
                $where[]=['is_on_sale','=',0];
            }else{
                $where[]=['is_on_sale','=',$is_on_sale];
            }
        }
        if ($keyword){
            $where[]=['goods_name','like',"%$keyword%"];
        }
        $goods=new FosterGoods();
        $list = $goods->where($where)->order('goods_id desc')->paginate([
            'query'=>['is_on_sale'=>$is_on_sale,'keyword'=>$keyword],
            'list_rows'=>$this->page_size
        ]);
        // 获取分页显示
        $page = $list->render();
        View::assign('list', $list);
        View::assign('page', $page);
        return view();
    }
    //审核认养商品
    public function check_forster_goods(){
        $ids=input('ids');
        $is_on_sale=input('is_on_sale');
        if (empty($ids)){
            throw new AdminException('请选择数据');
        }
        if (!in_array($is_on_sale,[-3,-2,-1,0,1])){
            throw new AdminException('提交参数有误');
        }
        $update['is_on_sale']=$is_on_sale;
        $res=FosterGoods::whereIn('goods_id',$ids)->save($update);
        throw new AdminException('操作成功',1);
    }
    //添加编辑认养商品
    public function add_edit_foster_goods(){
        $goods_id=input('goods_id');
        $images=$foster_goods_extra=[];
        $goods=new FosterGoods();
        if ($goods_id){
            $info=$goods->find($goods_id);
            if ($info['goods_imgs']){
                $arr=['mp4','3gp'];
                foreach ($info['goods_imgs'] as $image){
                    $pathInfo=pathinfo($image);
                    $fileValueSuffix=strtolower($pathInfo['extension']);
                    if (in_array($fileValueSuffix,$arr)){
                        $map['type']='video';
                    }else{
                        $map['type']='image';
                    }
                    $map['src']=$image;
                    $images[]=$map;
                }
            }
            if ($info['extra_text']){
                foreach ($info['extra_text'] as $ex){
                    $map['lq_time']=date('Y-m-d H:i:s',$ex['lq_time']);
                    $map['number']=$ex['number'];
                    $map['id']=date('YmdHis').rand(1000,9999);
                    $foster_goods_extra[]=$map;
                }
            }
        }else{
            $info['is_on_sale']=1;
        }
        if (IS_POST){
            $data=input('post.');
            try {
                validate(\app\admin\validate\FosterGoods::class)->batch(true)->check($data);
            }catch (ValidateException $e){
                $error=$e->getError();
                $values=array_values($error);
                $result['result']=$error;
                throw new AdminException($values[0],10,$result);
            }
            $extra_wid = input('extra_wid');
            $extra_text = input('extra_text/a');
            if ($extra_text && $extra_wid>0){
                foreach ($extra_text as $key => $item){
                    if (empty($item["lq_time"])){
                        $msg=sprintf('请选择领取时间');
                        throw new AdminException($msg);
                    }
                    if (empty($item["number"])){
                        $msg=sprintf('请输入金额');
                        throw new AdminException($msg);
                    }
                    $extra_text[$key]['lq_time']=strtotime($item['lq_time']);
                }
                $data['extra_text']=$extra_text;
            }else{
                $data['extra_text']=[];
            }
            if ($goods_id){
                $res=$info->save($data);
                $new_goods_id=$goods_id;
            }else{
                $res=$goods->save($data);
                $new_goods_id=$goods->goods_id;
            }
            if ($res){
                $goods_sn = "CSMC".str_pad($new_goods_id,7,"0",STR_PAD_LEFT);
                Db::name('foster_goods')->where("goods_id = $new_goods_id and goods_sn = ''")->save(["goods_sn"=>$goods_sn]); // 根据条件更新记录
                adminLog($goods_id?"编辑认养商品":"添加认养商品");
                $data['url']=url('Goods/foster_goods_list')->build();
                throw new AdminException('操作成功',1,$data);
            }else{
                throw new AdminException('操作失败');
            }
        }
        $wallet=Wallet::where('1=1')->column('id,name');
        $store_list=\app\common\model\Store::where('status=1')->column('store_id,store_name');
        $cate_list=FosterGoodsCategory::where('1=1')->column('id,name');
        View::assign('cate_list', $cate_list);
        View::assign('store_list', $store_list);
        View::assign('wallet', $wallet);
        View::assign('info', $info);
        View::assign('images', $images);
        View::assign('foster_goods_extra', $foster_goods_extra);
        return view();
    }
    //删除认养商品
    public function delFosterGoods()
    {
        $ids = input('post.ids','');
        if (empty($ids)){
            throw new AdminException('请选择数据');
        }
        $ids_arr=implode(',',$ids);
        $goods_ids = rtrim($ids_arr,",");
        // 判断此商品是否有订单
        $ordergoods_count = Db::name('foster_order')->whereIn('goods_id',$goods_ids)->group('goods_id')->column('goods_id');
        if($ordergoods_count) {
            $goods_count_ids = implode(',',$ordergoods_count);
            throw new AdminException("ID为【{$goods_count_ids}】的商品有订单,不得删除!");
        }
        // 删除此商品
        Db::name("foster_goods")->whereIn('goods_id',$goods_ids)->delete();  //商品表
        adminLog("删除认养商品");
        throw new AdminException('操作成功',1);
    }
    //商品分类
    public function category_list(){
        // 搜索条件
        $where = [];
        $is_show=input('is_show');
        $keyword=input('keyword');
        if ($is_show!=''){
            $where[]=['is_show','=',$is_show];
        }
        if ($keyword){
            $where[]=['name','like',"%$keyword%"];
        }
        $goods_category=new GoodsCategory();
//        $cate_list=$goods_category->goods_cat_list();
        $list=$goods_category::where($where)->paginate([
            'query'=>['is_show'=>$is_show,'keyword'=>$keyword],
            'list_rows'=>$this->page_size
        ]);
        // 获取分页显示
        $page = $list->render();
        View::assign('list', $list);
        View::assign('page', $page);
        return view();
    }
    //添加编辑分类
    public function add_edit_category(){
        $id=input('id');
        $goods_category=new GoodsCategory();
        if ($id){
            $info=$goods_category->find($id);
        }else{
            $info['is_show']=1;
        }
        if (IS_POST){
            $data=input('post.');
            try {
                validate(\app\admin\validate\GoodsCategory::class)->batch(true)->check($data);
            }catch (ValidateException $e){
                $error=$e->getError();
                $values=array_values($error);
                $result['result']=$error;
                throw new AdminException($values[0],10,$result);
            }
            if ($data['parent_id']){
                $data['level']=2;
            }else{
                $data['level']=1;
            }
            if ($data['level']==1 && empty($data['image'])){
                throw new AdminException('请上传分类图片');
            }
            if ($id){
                $res=$info->save($data);
            }else{
                $res=$goods_category->save($data);
            }
            if ($res){
                adminLog($id?"编辑分类":"添加分类");
                $data['url']=url('Goods/category_list')->build();
                throw new AdminException('操作成功',1,$data);
            }else{
                throw new AdminException('操作失败');
            }
        }
        $cat_list_where[]=['level','=',1];
        if ($id){
            $cat_list_where[]=['id','<>',$id];
        }
        $cat_list = $goods_category->where($cat_list_where)->column('name,id');
        View::assign('cat_list',$cat_list);
        View::assign('info', $info);
        return view();
    }
    //模型列表
    public function goods_type_list(){
        // 搜索条件
        $where = [];
        $list=GoodsType::where($where)->paginate($this->page_size);
        // 获取分页显示
        $page = $list->render();
        View::assign('list', $list);
        View::assign('page', $page);
        return view();
    }
    //商品模型编辑页
    public function type()
    {
        $id = input('id/d');
        if($id){
            $goods_type = GoodsType::find($id);
            View::assign('goods_type', $goods_type);
        }
        return view();
    }
    //商品模型保存
    public function saveType()
    {
        $data = input('post.');
        try {
            validate(\app\admin\validate\GoodsType::class)->check($data);
        }catch (ValidateException $e){
            $error=$e->getError();
            throw new AdminException($error);
        }
        if ($data['id'] > 0) {
            $goodsType = GoodsType::find($data['id']);
        }else{
            $goodsType = new GoodsType();
        }
        $res=$goodsType->data($data, true)->save();
        if ($res){
            throw new AdminException('操作成功',1,['type_id'=>$goodsType->id]);
        }else{
            throw new AdminException('操作失败');
        }
    }
    //删除商品模型
    public function deleteType()
    {
        $id = input('id/d');
        if(empty($id)){
            throw new AdminException('参数错误');
        }
        $GoodsType = new GoodsType();
        $goods_type = $GoodsType->where(['id'=>$id])->find();
        $res=$goods_type->delete();
        if ($res){
            throw new AdminException('删除成功',1);
        }else{
            throw new AdminException('操作失败');
        }
    }
    //删除规格项
    public function deleteSpec()
    {
        $id = input('id/d');
        if (empty($id)) {
            throw new AdminException('参数错误');
        }
        $Spec = new Spec();
        $spec = $Spec->find($id);
        if ($spec->isEmpty()){
            throw new AdminException('删除失败,规格不存在!');
        }else{
            $spec->delete();
            throw new AdminException('删除成功',1);
        }
    }
    //删除规格值
    public function deleteSpecItem()
    {
        $id = input('id/d');
        if (empty($id)) {
            throw new AdminException('参数错误');
        }
        $SpeItem = new SpecItem();
        $spec_item = $SpeItem->find($id);
        if ($spec_item->isEmpty()){
            throw new AdminException('删除失败,规格不存在!');
        }else{
            $spec_item->delete();
            throw new AdminException('删除成功',1);
        }
    }
    /**
     * 获取商品模型下拉列表
     */
    public function ajaxGetGoodsTypeList($type_id)
    {
        $GoodsType = new GoodsType();
        $goods_type = $GoodsType->select();

        $html = '<option value="0">选择商品模型';
        foreach ($goods_type as $v){
            $html .= "<option value='{$v['id']}'";
            if($type_id == $v['id']){
                $html .= ' selected="selected" ';
            }
            $html .= ">{$v['name']}</option>";
        }
        exit(json_encode($html, JSON_UNESCAPED_UNICODE));
    }
    /**
     * 动态获取商品规格选择框 根据不同的数据返回不同的选择框
     */
    public function ajaxGetSpecSelect()
    {
        $goods_id = input('goods_id/d', 0);
        $type_id = input('type_id/d', 0);
        $specList = Db::name('spec')->where("type_id", $type_id)->order('sort asc')->select()->toArray();
        foreach ($specList as $k => $v){
            $spec_item=Db::name('spec_item')->where("spec_id" , $v['id'])->order('id')->column('item','id'); // 获取规格项
            $specList[$k]['spec_item'] = $spec_item;
        }
        $items_id = Db::name('spec_goods_price')->where('goods_id', $goods_id)->value("GROUP_CONCAT(`key` SEPARATOR '_') AS items_id");
        $items_ids = explode('_', $items_id);
        // 获取商品规格图片
        if ($goods_id) {
            $specImageList = Db::name('spec_image')->where("goods_id", $goods_id)->column('src','spec_image_id');
            View::assign('specImageList', $specImageList);
        }
        View::assign('items_ids', $items_ids);
        View::assign('specList', $specList);
        return view('ajax_spec_select');
    }
    /**
     * 动态获取商品规格输入框 根据不同的数据返回不同的输入框
     */
    public function ajaxGetSpecInput(){
        $GoodsLogic = new \app\common\model\Goods();
        $goods_id = input('goods_id/d') ? input('goods_id/d') : 0;
        $str = $GoodsLogic->getSpecInput($goods_id ,input('post.spec_arr/a',[[]]));
        exit($str);
    }
    /**
     * 删除商品相册图
     */
    public function del_goods_images()
    {
        $path = input('filename','');
        Db::name('goods_images')->where("image_url",$path)->delete();
    }
    //分类列表
    public function classify_index(){
        // 搜索条件
        $where = [];
        $is_open = input('is_open');
        $keyword = input('keyword');
        if ($is_open!=''){
            $where[]=['is_open','=',$is_open];
        }
        if ($keyword){
            $where[]=['name','like',"%$keyword%"];
        }
        $list = MonitorClass::where($where)->paginate([
            'query'=>['is_open'=>$is_open,'keyword'=>$keyword],
            'list_rows'=>$this->page_size
        ]);

        // 获取分页显示
        $page = $list->render();
        View::assign('list', $list);
        View::assign('page', $page);
        return view();
    }
    //添加编辑分类
    public function add_edit_classify(){
        $id=input('id');
        $model=new MonitorClass();
        if ($id){
            $info=$model->find($id);
        }else{
            $info['is_open']=1;
        }
        if (IS_POST){
            $data=input('post.');
            try {
                validate(\app\admin\validate\MonitorClass::class)->batch(true)->check($data);
            }catch (ValidateException $e){
                $error=$e->getError();
                $values=array_values($error);
                throw new AdminException($values[0],10,['result'=>$error]);
            }

            if ($id){
                $res=$info->save($data);
            }else{
                $res=$model->save($data);
            }
            if ($res){
                adminLog($id?"编辑监控分类":"添加监控分类");
                throw new AdminException('操作成功',1,['url'=>url('Goods/classify_index')->build()]);
            }else{
                throw new AdminException('操作失败');
            }
        }
        View::assign('info', $info);
        return view();
    }
    //监控
    public function monitor_index(){
        // 搜索条件
        $where = [];
        $is_open = input('is_open');
        $keyword = input('keyword');
        if ($is_open!=''){
            $where[]=['is_open','=',$is_open];
        }
        if ($keyword){
            $where[]=['name','like',"%$keyword%"];
        }
        $list = Monitors::where($where)->paginate([
            'query'=>['is_open'=>$is_open,'keyword'=>$keyword],
            'list_rows'=>$this->page_size
        ]);

        // 获取分页显示
        $page = $list->render();
        View::assign('list', $list);
        View::assign('page', $page);
        return view();
    }
    //添加编辑monitors
    public function add_edit_monitor(){
        $id=input('id');
        $model=new Monitors();
        if ($id){
            $info=$model->find($id);
        }else{
            $info['is_open']=1;
        }
        if (IS_POST){
            $data=input('post.');
            try {
                validate(\app\admin\validate\Monitors::class)->batch(true)->check($data);
            }catch (ValidateException $e){
                $error=$e->getError();
                $values=array_values($error);
                throw new AdminException($values[0],10,['result'=>$error]);
            }

            if ($id){
                if($data['serial']!=$info['serial']){
                    //添加监控设备
                    $Http = new HttpClient();
                    $result=$Http->addMonitor($data['serial'],$data['code']);
                    if($result['code']!=200){
                        throw new AdminException($result['msg']);
                    }
                    $Http->deleteMonitor($info['serial']);
                }
                $res=$info->save($data);
            }else{
                //添加监控设备
                $Http = new HttpClient();
                $result=$Http->addMonitor($data['serial'],$data['code']);
                if($result['code']!=200){
                    throw new AdminException($result['msg']);
                }
                $res=$model->save($data);
            }
            if ($res){
                adminLog($id?"编辑监控":"添加监控");
                throw new AdminException('操作成功',1,['url'=>url('Goods/monitor_index')->build()]);
            }else{
                throw new AdminException('操作失败');
            }
        }
        View::assign('info', $info);
        $class=MonitorClass::where('is_open',1)->select();
        View::assign('class', $class);
        return view();
    }
}
